package com.faxon.leetcode.c;

import org.junit.Test;

/**
 * @author Faxon
 * @version 1.0
 * @date 2020-04-13 17:43
 * 21. 合并两个有序链表
 * 将两个升序链表合并为一个新的升序链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。 
 * 示例：
 * 输入：1->2->4, 1->3->4
 * 输出：1->1->2->3->4->4
 **/
public class LeetCode21 {
    public static class ListNode {
        int val;
        ListNode next;

        ListNode(int x) {
            val = x;
        }

        @Override
        public String toString() {
            return "ListNode{" +
                    "val=" + val +
                    ", next=" + next +
                    '}';
        }
    }

    public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
        if (l1 == null) {
            return l2;
        }
        if (l2 == null) {
            return l1;
        }
        ListNode result = new ListNode(0);
        ListNode one = l1, two = l2, r = result;
        while (true) {
            if (one.val <= two.val) {
                r.next = new ListNode(one.val);
                r = r.next;
                if (one.next != null) {
                    one = one.next;
                }else {
                    r.next = two;
                    break;
                }
            } else {
                r.next = new ListNode(two.val);
                r = r.next;
                if (two.next != null) {
                    two = two.next;
                }else {
                    r.next = one;
                    break;
                }
            }
        }
        return result.next;
    }

    @Test
    public void testMergeTwoLists() {
        ListNode l1 = new ListNode(1);
        l1.next = new ListNode(3);
        l1.next.next = new ListNode(4);


        ListNode l2 = new ListNode(2);
        l1.next = new ListNode(4);
        l1.next.next = new ListNode(5);

        ListNode listNode = mergeTwoLists(l1, l2);
        System.out.println(listNode);
    }
}
